package com.molichuxing.services.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.molichuxing.services.business.convertor.Convert;
import com.molichuxing.services.business.dto.response.*;
import com.molichuxing.services.infrastructure.dto.request.create.OrderStatusFlowCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.OrderDealerStartStatusModifyDto;
import com.molichuxing.services.infrastructure.dto.response.OrderDealerDetailBasicDto;
import com.molichuxing.services.infrastructure.service.OrderStatusFlowService;
import com.molichuxing.services.property.OrderDealerSendCarStatusEnum;
import com.molichuxing.services.property.OrderRequestTypeEnum;
import com.molichuxing.services.property.OrderScheduleStatusEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.services.business.service.OrderDealerBizService;
import com.molichuxing.services.infrastructure.dto.response.OrderDealerDetailCarInfoDto;
import com.molichuxing.services.infrastructure.dto.response.OrderDealerDetailStartDto;
import com.molichuxing.services.infrastructure.dto.response.OrderDealerDto;
import com.molichuxing.services.infrastructure.service.OrderDealerDeliveryService;
import com.molichuxing.services.infrastructure.service.OrderDealerService;
import com.molichuxing.services.infrastructure.service.OrderScheduleService;
import com.molichuxing.services.property.OrderDealerStatusEnum;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 17:23 2019/8/14
 * @Modified By:
 **/
@Service("orderDealerBizService")
public class OrderDealerBizServiceImpl implements OrderDealerBizService {

    @Autowired
    private OrderDealerService orderDealerService;

    @Autowired
    private OrderDealerDeliveryService orderDealerDeliveryService;

    @Autowired
    private OrderScheduleService orderScheduleService;

    @Autowired
    private OrderStatusFlowService orderStatusFlowService;

    @Override
    public Paged<OrderDealerBizDto> getOrderDealerBusList(Map<String, Object> params, Integer pageNum, Integer pageSize,OrderRequestTypeEnum requestType) {
        //查询基础列表信息
        Paged<OrderDealerDto> orderDealerPage = orderDealerService.getOrderDealerList(params, pageNum, pageSize,requestType);
        Paged<OrderDealerBizDto> busPage = new Paged<>();
        if (orderDealerPage != null && orderDealerPage.getList() != null) {
            List<OrderDealerDto> orderDealerDtoList = orderDealerPage.getList();
            List<OrderDealerBizDto> orderDealerBizDtoList = new ArrayList<>();
            OrderDealerBizDto orderDealerBizDto = null;
            for (OrderDealerDto orderDealerDto : orderDealerDtoList) {
                orderDealerBizDto = new OrderDealerBizDto();
                BeanUtils.copyProperties(orderDealerDto, orderDealerBizDto);
                //查询每个订单关联的车辆id
                List<Integer> carIdList = orderDealerDeliveryService.getCarIdListByOrderCode(orderDealerDto.getOrderCode());
                //查询付款金额
                if(OrderDealerStatusEnum.CREATE_ORDER.getValue() == orderDealerDto.getOrderStatus() || OrderDealerStatusEnum.PREPAID_DOWN_PAYMENT.getValue() == orderDealerDto.getOrderStatus()){
                    BigDecimal downPayment = orderScheduleService.getDownPaymentByOrderCode(orderDealerDto.getOrderCode());
                    orderDealerBizDto.setDownPayment(downPayment == null ? new BigDecimal("0"):downPayment);
                }else if(OrderDealerStatusEnum.DOWN_PAYMENT_PAID.getValue() == orderDealerDto.getOrderStatus()){
                    BigDecimal amountPaid = orderScheduleService.getAmountPaidByOrderCode(orderDealerDto.getOrderCode(), OrderScheduleStatusEnum.TRADE_UNAUDIT.getValue());
                    orderDealerBizDto.setAmountPaid(amountPaid == null ? new BigDecimal("0"):amountPaid);
                }else{
                    BigDecimal amountPaid = orderScheduleService.getAmountPaidByOrderCode(orderDealerDto.getOrderCode(), OrderScheduleStatusEnum.ALREADY.getValue());
                    orderDealerBizDto.setAmountPaid(amountPaid == null ? new BigDecimal("0"):amountPaid);
                }

                orderDealerBizDto.setCarIdList(carIdList);
                orderDealerBizDtoList.add(orderDealerBizDto);
            }

            busPage.setList(orderDealerBizDtoList);
        }
        busPage.setPageNum(orderDealerPage.getPageNum());
        busPage.setPageSize(orderDealerPage.getPageSize());
        busPage.setPages(orderDealerPage.getPages());
        busPage.setTotal(orderDealerPage.getTotal());
        busPage.setTab(orderDealerPage.getTab());
        return busPage;
    }

    @Override
    public OrderDealerDeliveryBizDto getOrderDetailCarsInfo(Long orderCode) throws Exception {

        if (orderCode == null) {
            throw new Exception("订单号不能为空");
        }
        Integer status = orderDealerService.getOrderDealerStatus(orderCode);
        if (status == null) {
            throw new Exception("无效订单");
        }
        OrderDealerDeliveryBizDto biz = new OrderDealerDeliveryBizDto();
        //查询订单关联车辆信息列表
        List<OrderDealerDetailCarInfoDto> carList = orderDealerDeliveryService.getDetailCarInfoDto(orderCode);
        if (carList == null || carList.size() == 0) {
            throw new Exception("无车辆信息");
        }
        List<OrderDealerDetailCarInfoBizDto> carBusList = Convert.toOrderDealerDetailCarInfoBizDto(carList);
        biz.setOrderDealerDetailCarInfoList(carBusList);

        //查询订单关联发车信息列表 只有订单状态为 等待收车 和 完成采购 才展示
        if(status == OrderDealerStatusEnum.WAIT_PICK_UP.getValue() || status == OrderDealerStatusEnum.COMPLETE.getValue()){
            List<OrderDealerDetailStartDto> startList = orderDealerDeliveryService.getDetailStartDto(orderCode,null);
            if (startList == null || startList.size() == 0) {
                throw new Exception("无发车信息");
            }
            List<OrderDealerDetailStartBizDto> startBusList = Convert.toOrderDealerDetailStartBizDto(startList);
            biz.setOrderDealerDetailStartList(startBusList);
        }

        return biz;
    }

    @Override
    public OrderDealerDetailBasicDto getDealerIdByCarId(Integer carId) throws Exception {

        Long orderCode = orderDealerDeliveryService.getOrderCodeBycarId(carId);
        if (null == orderCode) {
           return null;
        }
        OrderDealerDetailBasicDto orderDealerDetailBasicDto = orderDealerService.getDetailBasic(orderCode);
        if (null == orderDealerDetailBasicDto) {
            return null;
        }

        return orderDealerDetailBasicDto;
    }

    @Override
    public Map<Integer,OrderDealerPaymentBizDto> getOrderDealerPayment(Integer dealerId, Integer carId) throws Exception {

        List<Long> orderCodeList = orderDealerService.getOrderCodeByDealerId(dealerId);
        if(null == orderCodeList || orderCodeList.size() <= 0){
            return null;
        }
        List<OrderDealerPaymentBizDto> orderDealerPaymentList = orderDealerDeliveryService.getOrderDealerPayment(orderCodeList,carId);
        if(null == orderDealerPaymentList || orderDealerPaymentList.size() <= 0){
            return null;
        }
        Map<Integer,OrderDealerPaymentBizDto> map = orderDealerPaymentList.stream().collect(Collectors.toMap(OrderDealerPaymentBizDto::getCarId, orderDealerPaymentBizDto -> orderDealerPaymentBizDto));
        return map;
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Boolean modifyBizCarStartStatus(OrderDealerStartStatusModifyDto orderDealerStartStatusModifyDto) throws Exception {

        if(null == orderDealerStartStatusModifyDto){
            throw new Exception("非法入参");
        }


        Long orderCode = orderDealerDeliveryService.getOrderCodeBycarId(orderDealerStartStatusModifyDto.getCarId());
        if(null == orderCode){
            throw new Exception("非法入参");
        }
        //查询订单下所有发车状态
        List<Integer> sendStatusList =  orderDealerDeliveryService.getSendStatusByOrderCode(orderCode);
        if(null == sendStatusList || sendStatusList.size() <= 0){
            throw new Exception("非法入参");
        }
        int count = 0;
        for (Integer sendStatus: sendStatusList) {
            if(sendStatus == OrderDealerSendCarStatusEnum.NO_RECEIVED.getValue()){
                count++;
                continue;
            }
        }

        //如果是当前订单下第一次发车，则将采购单状态改为等待收车
        if(count == 0 ){
            Boolean modifyOrderStatus = orderDealerService.modifyOrderStatus(orderCode, OrderDealerStatusEnum.WAIT_PICK_UP.getValue());

            OrderStatusFlowCreateDto orderStatusFlowCreateDto= new OrderStatusFlowCreateDto();
            orderStatusFlowCreateDto.setOrderCode(orderCode);
            orderStatusFlowCreateDto.setOrderStatus(OrderDealerStatusEnum.WAIT_PICK_UP.getValue());
            //获取登录用户信息  操作人id，操作人名称，操作人类型，
            orderStatusFlowCreateDto.setOrderUserId(orderDealerStartStatusModifyDto.getOperatorId());
            orderStatusFlowCreateDto.setOrderUserName(orderDealerStartStatusModifyDto.getOperatorName());
            //订单流转状态插入
            Boolean createOrderStatusFlow =orderStatusFlowService.createOrderStatusFlow(orderStatusFlowCreateDto);
            if(!modifyOrderStatus || !createOrderStatusFlow){
                return false;
            }
        }

        //修改车辆的发车状态
        orderDealerStartStatusModifyDto.setOrderCode(orderCode);
        Boolean modifyCarStartStatus =  orderDealerDeliveryService.modifyCarStartStatus(orderDealerStartStatusModifyDto);
        if(!modifyCarStartStatus ){
            return false;
        }


        return true;
    }
}
